<template>
  <div class="tongue">
    <!-- 截图弹窗组件 -->
    <cutimg :isshow="modleshow" :img="imgurl" @getimgurl="getimgurl" @clear="clear"/>
    <!-- 遮罩层 -->
    <van-overlay :show="show">
      <div class="wrapper">
        <van-loading text-color="#0094ff" color="#0094ff" size="28px">上传中...</van-loading>
      </div>
    </van-overlay>
    <div class="upload">
      <van-uploader v-model="fileList" :after-read="afterRead" />
    </div>
    <div class="btn-group">
      <van-button type="primary" @click="handleUpload">上传</van-button>
    </div>
  </div>
</template>
<script>
import { tongUp } from "../../utils/api";
import { Toast } from "vant";
import cutimg from "@/components/cutimg";
export default {
  name: "tongue",
  components: {
    cutimg,
  },
  data() {
    return {
      show: false,   // 遮罩层
      fileList: [],    // 图片预览
      resp: {},      // 存留返回数据
      modleshow: false,   //图片裁剪弹窗      
      imgurl: "",  //要裁剪的图片
    };
  },
  methods: {
    //获得组件传过来的图片
    getimgurl(e) {
      //删除原来的图片
      this.fileList.pop();
      //添加截图过后的
      this.fileList.push(e);
      this.modleshow = false;
    },
    //取消截图 关闭
    clear() {
      this.modleshow = false;
    },
    //上传前处理
    afterRead(_file) {
      //const hasArr = Object.prototype.toString.call(_file) == "[object Array]";
      const { file } = _file;
      const { type } = file;
      const isIMG = ["image/jpeg", "image/jpg", "image/png"];
      if (!isIMG.includes(type)) {
        Toast("请上传图片");
        return false;
      }
      //console.log(_file);
      this.imgurl = _file.content;
      this.modleshow = true;
      return true;
    },

     //调取图片上传接口
    async handleUpload() {
      try {
        const { fileList } = this;
        //console.log(fileList);
        if (!fileList.length) return Toast("请先上传图片");
        const params = new FormData();
        for (let item of fileList) {
          params.append("image", item.file);
        }
        console.log(params.getAll("image"), "上传图片传的参数");
        this.show = true;
        const res = await tongUp(params);
        console.log(res, "上传图片返回的数据");
        const { data } = res;
        const { msg } = data;
        const resp = JSON.stringify(res.data);
        const query = {
          resp,
        };
        if (msg == "succeed") {
          this.$router.push({
            path: "/tongue/discernResult",
            query,
          });
        } else {
          Toast(msg);
        }
        this.show = false;
      } catch (err) {
        this.show = false;
        console.log(err);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.tongue {
  padding: 15px;
  margin-top: 20px;
}
.upload {
  display: flex;
  justify-content: center;
}
.btn-group {
  width: 100%;
  margin-top: 8px;
}
.btn-group button {
  width: 100%;
  border-radius: 1rem;
}
</style>
